package no.cicero.testframework.xml.testcase;

import no.cicero.testframework.common.xml.XmlImporter;
import no.cicero.testframework.common.xml.XmlTag;
import no.cicero.testframework.model.testcase.TestCase;
import no.cicero.testframework.xml.IXmlNameTable;
import no.cicero.testframework.xml.XmlImporterValidation;
import org.xml.sax.SAXException;

import javax.xml.parsers.SAXParser;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;

public class TestCaseImporter extends XmlImporterValidation implements IXmlNameTable.ITestCaseTag{
    private final static String SCHEMA_FILE = "tcSchema.xsd";

    private TestCase testCase = null;
    public TestCase getTestCase() { return testCase; }

    private StepImporter stepDelegate = null;

    public TestCaseImporter(SAXParser p){
        super(p, SCHEMA_FILE);
    }

    public TestCase doImport(String servicePath) throws SAXException, IOException {
        return doImport(new File(servicePath));
    }

    public TestCase doImport(File servicePath) throws SAXException, IOException {
        testCase = null;

        validateStream(new FileInputStream(servicePath));

        super.doImport(new FileInputStream(servicePath));
        return testCase;
    }

    public TestCase doImportFromStream(InputStream is) throws SAXException, IOException {
        testCase = null;
        // no valiation

        super.doImport( is );

        return testCase;
    }

    //----interface IXmlImporter
    @Override
    public void handleStartElement(XmlImporter importer, XmlTag tag) throws SAXException {
        if( tag.getName().equalsIgnoreCase( ROOT_ELEMENT ) ) {
            testCase = new TestCase();
        } else if( tag.getParent().getName().equalsIgnoreCase(ROOT_ELEMENT) && tag.getName().equalsIgnoreCase( STEP_ELEMENT ) ) {
            stepDelegate = new StepImporter(testCase);
            pushDelegate(stepDelegate);
        } else
            StepParametersImporterHelper.handleStartElement(importer, tag, testCase);
    }

    @Override
    public void handleEndElement(XmlImporter importer, XmlTag tag) throws SAXException {
        if (tag.getName().equalsIgnoreCase(STEP_ELEMENT) && tag.getParent().getName().equalsIgnoreCase(ROOT_ELEMENT)) {
            testCase.addStep(stepDelegate.getStep());
            stepDelegate = null;
        }
    }

    @Override
    public void handleText(XmlImporter importer, XmlTag tag, String text) throws SAXException {
        if (tag.getParent().getName().equalsIgnoreCase(ROOT_ELEMENT)) {
            StepParametersImporterHelper.handleText(importer, tag, text, testCase);
        }
    }

}
